package api;

import com.fasterxml.jackson.databind.ObjectMapper;
import dao.Blog;
import dao.BlogDao;
import dao.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.function.DoublePredicate;

@WebServlet("/blog")
public class BlogServlet extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();//构造出一个对象

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 查询数据库, 获取到数据之后, 构造成要求的 json 格式并返回.
        BlogDao blogDao=new BlogDao();
        //获取blog_id
        String blogId=req.getParameter("blogId");
        if(blogId==null)
        {
            //获取失败，或者没有
            //此时说明是获取博客详情，没有blog参数
            List<Blog> blogs=blogDao.getBlogs();
            //将每一个数据构造成json对象
            String respJson=objectMapper.writeValueAsString(blogs);
            resp.setContentType("application/json; charset=utf8");
            resp.getWriter().write(respJson);//写回响应


        }
        else
        {
            Blog blog=blogDao.getBlog(Integer.parseInt(blogId));
            if(blog==null)
            {
                blog=new Blog();
                //返回一个blogId为零的对象

            }
            String respJson=objectMapper.writeValueAsString(blog);
            resp.setContentType("application/json; charset=utf8");
            resp.getWriter().write(respJson);//写回响应

        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf8");
        HttpSession session=req.getSession(false);
        if(session==null)
        {
            resp.getWriter().write("未登录");
            resp.sendRedirect("login.html");
            return;
        }
        User user=(User) session.getAttribute("user");
        BlogDao blogDao=new BlogDao();//数据库连接
        String title=req.getParameter("title");//获取到标题和内容
        String content=req.getParameter("content");
        //判断当前内容是不空
        if(title==null || content==null ||title.equals("") || content.equals(""))
        {
            resp.setContentType("application/json; charset=utf8");
            resp.getWriter().write("标题或正文为空");
            return;
        }
        //有标题和正文后插入数据库
        Blog blog=new Blog();
        blog.setTitle(title);
        blog.setContent(content);
        blog.setUserId(user.getUserId());
        blog.setPostTime(new Timestamp(System.currentTimeMillis()));//可不写，sql里写了now
        blogDao.insert(blog);//将博客添加到数据库中
        resp.sendRedirect("blog_list.html");

    }
}
